/**
 * 尝试跟踪系统
 * 简单的JSON跟踪系统，用于3次尝试验证规则
 */

const fs = require('fs');
const path = require('path');

const STATE_FILE = '.todo-attempts.json';

/**
 * 加载尝试跟踪数据
 * @returns {Object} 跟踪数据
 */
function loadAttempts() {
    try {
        if (fs.existsSync(STATE_FILE)) {
            const data = fs.readFileSync(STATE_FILE, 'utf8');
            return JSON.parse(data);
        }
    } catch (error) {
        console.warn('加载尝试跟踪数据失败:', error.message);
    }

    return {
        tasks: {},
        lastUpdated: null
    };
}

/**
 * 保存尝试跟踪数据
 * @param {Object} data 跟踪数据
 * @returns {boolean} 是否保存成功
 */
function saveAttempts(data) {
    try {
        data.lastUpdated = new Date().toISOString();
        fs.writeFileSync(STATE_FILE, JSON.stringify(data, null, 2));
        return true;
    } catch (error) {
        console.error('保存尝试跟踪数据失败:', error.message);
        return false;
    }
}

/**
 * 为任务生成唯一ID
 * @param {string} taskContent 任务内容
 * @returns {string} 任务ID
 */
function generateTaskId(taskContent) {
    // 简单的哈希函数，基于任务内容生成ID
    let hash = 0;
    for (let i = 0; i < taskContent.length; i++) {
        const char = taskContent.charCodeAt(i);
        hash = ((hash << 5) - hash) + char;
        hash = hash & hash; // 转换为32位整数
    }
    return `task-${Math.abs(hash)}`;
}

/**
 * 开始新的任务尝试
 * @param {string} taskContent 任务内容
 * @param {Object} options 选项
 * @returns {Object} 尝试信息
 */
function startAttempt(taskContent, options = {}) {
    const {
        approach = 'manual',      // 实现方式
        maxAttempts = 3          // 最大尝试次数
    } = options;

    const taskId = generateTaskId(taskContent);
    const data = loadAttempts();

    // 初始化任务记录（如果不存在）
    if (!data.tasks[taskId]) {
        data.tasks[taskId] = {
            content: taskContent,
            attempts: [],
            currentApproach: approach,
            status: 'pending',      // pending, in_progress, completed, deferred
            createdAt: new Date().toISOString()
        };
    }

    const task = data.tasks[taskId];
    const attemptNumber = task.attempts.length + 1;

    // 检查是否超过最大尝试次数
    if (attemptNumber > maxAttempts) {
        return {
            success: false,
            error: `已超过最大尝试次数 (${maxAttempts})`,
            taskId: taskId,
            attemptNumber: attemptNumber,
            remainingAttempts: 0
        };
    }

    // 创建新的尝试记录
    const attempt = {
        number: attemptNumber,
        approach: approach,
        startTime: new Date().toISOString(),
        endTime: null,
        duration: null,
        result: null,             // success, failure, error
        details: null,
        gitCommit: null
    };

    task.attempts.push(attempt);
    task.status = 'in_progress';
    task.currentApproach = approach;

    // 保存数据
    saveAttempts(data);

    return {
        success: true,
        taskId: taskId,
        attemptNumber: attemptNumber,
        remainingAttempts: maxAttempts - attemptNumber,
        approach: approach,
        attemptId: `${taskId}-${attemptNumber}`
    };
}

/**
 * 完成当前尝试
 * @param {string} taskId 任务ID
 * @param {string} result 结果 (success, failure, error)
 * @param {Object} details 详细信息
 * @returns {Object} 完成结果
 */
function completeAttempt(taskId, result, details = {}) {
    const data = loadAttempts();
    const task = data.tasks[taskId];

    if (!task) {
        return {
            success: false,
            error: '任务不存在',
            taskId: taskId
        };
    }

    if (task.attempts.length === 0) {
        return {
            success: false,
            error: '没有进行中的尝试',
            taskId: taskId
        };
    }

    // 获取当前尝试
    const currentAttempt = task.attempts[task.attempts.length - 1];

    if (currentAttempt.endTime) {
        return {
            success: false,
            error: '当前尝试已经完成',
            taskId: taskId,
            attemptNumber: currentAttempt.number
        };
    }

    // 完成尝试
    currentAttempt.endTime = new Date().toISOString();
    currentAttempt.duration = Date.now() - new Date(currentAttempt.startTime).getTime();
    currentAttempt.result = result;
    currentAttempt.details = details;

    // 更新任务状态
    if (result === 'success') {
        task.status = 'completed';
        task.completedAt = new Date().toISOString();
    } else if (task.attempts.length >= 3) {
        task.status = 'deferred';
        task.deferredAt = new Date().toISOString();
        task.deferredReason = details.reason || '3次尝试失败';
    } else {
        task.status = 'pending'; // 可以再次尝试
    }

    // 保存数据
    saveAttempts(data);

    return {
        success: true,
        taskId: taskId,
        attemptNumber: currentAttempt.number,
        result: result,
        taskStatus: task.status,
        totalAttempts: task.attempts.length,
        remainingAttempts: Math.max(0, 3 - task.attempts.length)
    };
}

/**
 * 获取任务的尝试信息
 * @param {string} taskContent 任务内容
 * @returns {Object} 任务信息
 */
function getTaskAttempts(taskContent) {
    const taskId = generateTaskId(taskContent);
    const data = loadAttempts();
    const task = data.tasks[taskId];

    if (!task) {
        return {
            taskId: taskId,
            exists: false,
            attempts: 0,
            status: 'none'
        };
    }

    return {
        taskId: taskId,
        exists: true,
        content: task.content,
        attempts: task.attempts.length,
        status: task.status,
        currentApproach: task.currentApproach,
        canAttempt: task.status === 'pending' && task.attempts.length < 3,
        remainingAttempts: Math.max(0, 3 - task.attempts.length),
        lastAttempt: task.attempts[task.attempts.length - 1] || null,
        createdAt: task.createdAt,
        completedAt: task.completedAt,
        deferredAt: task.deferredAt,
        deferredReason: task.deferredReason
    };
}

/**
 * 检查是否需要更换实现方式
 * @param {string} taskContent 任务内容
 * @param {string} newApproach 新的实现方式
 * @returns {boolean} 是否需要更换
 */
function needsApproachChange(taskContent, newApproach) {
    const taskInfo = getTaskAttempts(taskContent);

    if (!taskInfo.exists || taskInfo.attempts < 3) {
        return false;
    }

    return taskInfo.currentApproach !== newApproach;
}

/**
 * 重置任务的尝试记录（更换实现方式时使用）
 * @param {string} taskContent 任务内容
 * @param {string} newApproach 新的实现方式
 * @returns {Object} 重置结果
 */
function resetAttempts(taskContent, newApproach) {
    const taskId = generateTaskId(taskContent);
    const data = loadAttempts();
    const task = data.tasks[taskId];

    if (!task) {
        return {
            success: false,
            error: '任务不存在',
            taskId: taskId
        };
    }

    const oldApproach = task.currentApproach;
    const oldAttempts = task.attempts.length;

    // 重置尝试记录
    task.attempts = [];
    task.currentApproach = newApproach;
    task.status = 'pending';
    task.lastReset = {
        timestamp: new Date().toISOString(),
        fromApproach: oldApproach,
        toApproach: newApproach,
        previousAttempts: oldAttempts
    };

    // 保存数据
    saveAttempts(data);

    return {
        success: true,
        taskId: taskId,
        oldApproach: oldApproach,
        newApproach: newApproach,
        previousAttempts: oldAttempts,
        message: `已重置尝试记录，从 '${oldApproach}' 更换为 '${newApproach}'`
    };
}

/**
 * 获取所有任务的统计信息
 * @returns {Object} 统计信息
 */
function getStats() {
    const data = loadAttempts();
    const tasks = Object.values(data.tasks);

    const stats = {
        totalTasks: tasks.length,
        byStatus: {
            pending: 0,
            in_progress: 0,
            completed: 0,
            deferred: 0
        },
        byApproach: {},
        totalAttempts: 0,
        successfulAttempts: 0,
        failedAttempts: 0,
        averageAttemptsPerTask: 0
    };

    tasks.forEach(task => {
        // 按状态统计
        if (stats.byStatus[task.status] !== undefined) {
            stats.byStatus[task.status]++;
        }

        // 按方式统计
        const approach = task.currentApproach;
        stats.byApproach[approach] = (stats.byApproach[approach] || 0) + 1;

        // 尝试统计
        stats.totalAttempts += task.attempts.length;

        task.attempts.forEach(attempt => {
            if (attempt.result === 'success') {
                stats.successfulAttempts++;
            } else if (attempt.result === 'failure' || attempt.result === 'error') {
                stats.failedAttempts++;
            }
        });
    });

    // 计算平均尝试次数
    if (stats.totalTasks > 0) {
        stats.averageAttemptsPerTask = stats.totalAttempts / stats.totalTasks;
    }

    return stats;
}

/**
 * 清理已完成或延期的任务记录
 * @param {number} olderThanDays 清理多少天前的记录
 * @returns {Object} 清理结果
 */
function cleanup(olderThanDays = 7) {
    const data = loadAttempts();
    const cutoffDate = new Date();
    cutoffDate.setDate(cutoffDate.getDate() - olderThanDays);

    const originalTaskCount = Object.keys(data.tasks).length;
    const removedTasks = [];

    // 遍历任务，标记需要清理的
    Object.keys(data.tasks).forEach(taskId => {
        const task = data.tasks[taskId];

        const shouldCleanup = (
            (task.status === 'completed' && task.completedAt && new Date(task.completedAt) < cutoffDate) ||
            (task.status === 'deferred' && task.deferredAt && new Date(task.deferredAt) < cutoffDate)
        );

        if (shouldCleanup) {
            removedTasks.push({
                taskId: taskId,
                content: task.content,
                status: task.status,
                completedAt: task.completedAt,
                deferredAt: task.deferredAt
            });
            delete data.tasks[taskId];
        }
    });

    // 保存清理后的数据
    saveAttempts(data);

    return {
        success: true,
        originalTaskCount: originalTaskCount,
        remainingTaskCount: Object.keys(data.tasks).length,
        removedCount: removedTasks.length,
        removedTasks: removedTasks
    };
}

// 如果直接运行此脚本，显示统计信息
if (require.main === module) {
    console.log('📊 尝试跟踪统计');
    console.log('='.repeat(30));

    const stats = getStats();

    console.log(`总任务数: ${stats.totalTasks}`);
    console.log(`总尝试次数: ${stats.totalAttempts}`);
    console.log(`成功尝试: ${stats.successfulAttempts}`);
    console.log(`失败尝试: ${stats.failedAttempts}`);
    console.log(`平均尝试次数: ${stats.averageAttemptsPerTask.toFixed(2)}`);
    console.log('');

    console.log('按状态统计:');
    Object.entries(stats.byStatus).forEach(([status, count]) => {
        if (count > 0) {
            console.log(`  ${status}: ${count}`);
        }
    });
    console.log('');

    if (Object.keys(stats.byApproach).length > 0) {
        console.log('按实现方式统计:');
        Object.entries(stats.byApproach).forEach(([approach, count]) => {
            console.log(`  ${approach}: ${count}`);
        });
    }

    // 显示最近的活动
    console.log('\n📝 最近活动:');
    const data = loadAttempts();
    const recentTasks = Object.values(data.tasks)
        .filter(task => task.status === 'in_progress' || task.status === 'pending')
        .slice(0, 3);

    if (recentTasks.length === 0) {
        console.log('  没有进行中的任务');
    } else {
        recentTasks.forEach(task => {
            const lastAttempt = task.attempts[task.attempts.length - 1];
            console.log(`  ${task.content.substring(0, 50)}... (${task.attempts.length} 次尝试)`);
        });
    }
}

module.exports = {
    loadAttempts,
    saveAttempts,
    generateTaskId,
    startAttempt,
    completeAttempt,
    getTaskAttempts,
    needsApproachChange,
    resetAttempts,
    getStats,
    cleanup
};